package org.csu.mypetstorebackstage.controller;

import org.csu.mypetstorebackstage.AccessProvider.AccessProvider;
import org.csu.mypetstorebackstage.AccessToken.ProviderToken;
import org.csu.mypetstorebackstage.domain.Account;
import org.csu.mypetstorebackstage.domain.Log;
import org.csu.mypetstorebackstage.domain.Manager;
import org.csu.mypetstorebackstage.domain.Order;
import org.csu.mypetstorebackstage.service.AccountService;
import org.csu.mypetstorebackstage.service.ManagerService;
import org.csu.mypetstorebackstage.service.OrderService;
import org.csu.mypetstorebackstage.util.Base64Coded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Properties;
import java.util.Random;

@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private ProviderToken providerToken;
    @Autowired
    private AccessProvider accessProvider;

    @GetMapping("/")
    public String Login(){return "common/login";}

    @GetMapping("/login2")
    public String giteeLog(@RequestParam(name="code") String code, @RequestParam(name="state") String state)
    {
        providerToken.setClient_id("06f7371ea094c8cd348de60ec50e01744cba07df0a8582ae5b591c63c8989e95");
        providerToken.setRedirect_url("http://localhost:8080/account/login2");
        providerToken.setCode(code);
        providerToken.setState(state);
        providerToken.setClient_secret("11fa67ddabb4af2eddb226f162c306efc148c4fbdb975a46b9d8aa063bc97013");
        accessProvider.getToken(providerToken);

        return "redirect:/account/viewMain";
    }

    @GetMapping("/toLogin")
    public String toLogin(){return "common/login";}

    @GetMapping("/viewMain")
    public String viewMain(){return "common/main";}

    @GetMapping("/sendVerification")
    public String sendVerification(String email, String password, String managerName, HttpSession session, Model model) throws MessagingException {

        Manager manager = managerService.getManagerByManagerName(managerName);

        session.setAttribute("managerName", managerName);
        session.setAttribute("password", password);
        if (manager!=null && email.equals(managerService.getEmailByManagerId(managerName))) {
            session.setAttribute("email", email);
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");
            props.put("mail.smtp.port", "587");
            props.put("mail.user", "441981719@qq.com");
            props.put("mail.password", "fabufdcypgxebjdb");
            Authenticator authenticator = new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password1 = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password1);
                }
            };
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
            message.setFrom(form);

            // 设置收件人的邮箱
            InternetAddress to = new InternetAddress(email);
            message.setRecipient(Message.RecipientType.TO, to);

            // 设置邮件标题
            message.setSubject("标题");

            // 设置邮件的内容体
            String sendVerification = "";
            Random random = new Random();
            for (int i = 0; i < 6; i++)
            {
                sendVerification += random.nextInt(10);
            }
            session.setAttribute("sendVerification", sendVerification);
            message.setContent(sendVerification, "text/html;charset=UTF-8");

            // 发送邮件
            Transport.send(message);

        } else {
            model.addAttribute("loginError", "email");
        }
        return "common/login";
    }

    //登录
    @PostMapping("/login")
    public String login(String managerName,String email ,String password, String verification, Model model, HttpSession session){
        Manager manager = managerService.getManagerByManagerName(managerName);
        System.out.println(Base64Coded.decode(manager.getPassword().getBytes()));
        String sendVerification = (String) session.getAttribute("sendVerification");
        session.setAttribute("managerName", managerName);
        session.setAttribute("email", email);
        session.setAttribute("password", password);
        System.out.println("pwd: "+password);
        if (manager==null||!Base64Coded.decode(manager.getPassword().getBytes()).equals(password)||!verification.equals(sendVerification)) {
            model.addAttribute("loginError", "password");
            return "common/login";
        } else {
            session.setAttribute("manager", manager);
            return "redirect:/category/returnMain";
        }
    }

    @PostMapping("/register")
    public String register(String managername,String password,String email, Model model, HttpSession session){
        password = Base64Coded.encode(password.getBytes());
        System.out.println("receive!!!"+managername+" and "+password+" and "+email);
        Manager manager = managerService.getManagerByManagerName(managername);
        if(manager == null){
            System.out.println("mark!!! false");
            model.addAttribute("registerOK","manager legal");
            managerService.addManager(managername,password,email);
            return "common/login";
        }else{
            System.out.println("mark!!!true");
            model.addAttribute("registerFail","manager name illegal");
            return "common/register";
        }

    }

    @GetMapping("toRegister")
    public String toRegister(){
        return "common/register";
    }

    @GetMapping("/viewAccounts")
    public  String viewAccounts(Model model){
        List<Account> accountList = accountService.getAllAccounts();
        model.addAttribute("accountList", accountList);
        return "/account/account";
    }

    @GetMapping("/viewAccountMessage")
    public String viewAccountMessage(String accountId, Model model){
        Account account = accountService.getAccountByUserId(accountId);
        model.addAttribute("account", account);
        return "account/accountMessage";
    }

    @GetMapping("/deleteAccount")
    public String deleteAccount(String accountId){
        accountService.deleteAccountByUserId(accountId);
        accountService.deleteAllLogsByUserId(accountId);
        return "redirect:/account/viewAccounts";
    }

    @GetMapping("/toAddAccount")
    public String toAddAccount(){
        return "account/addAccount";
    }

    @RequestMapping("/addAccount")
    public String addAccount(Model model, String username, String password, String firstname, String lastname, String email, String phone, String address1, String address2, String city, String state, String zip, String country, String languagePreference, String favouriteCategoryId, String listOption, String bannerOption){
        boolean k = true;
        if(!zip.matches("[0-9]+"))
        {
            k = false;
        }
        boolean myList;
        myList = listOption != null;
        boolean myBanner;
        myBanner = bannerOption != null;
        if(k)
        {
            Account account = new Account(username,password,firstname,lastname,email,phone,address1,address2,city,state,zip,country,languagePreference,favouriteCategoryId,myList,myBanner);
            if(accountService.getAccountByUserId(username) == null)
            {
                accountService.insertAccount(account);
                model.addAttribute("account",account);
                return "redirect:/account/viewAccounts";
            }
            else
            {
                model.addAttribute("registerError","username");
                return "account/addAccount";
            }
        }
        else
        {
            model.addAttribute("registerError","zip");
            return "account/addAccount";
        }
    }

    @GetMapping("/toEditAccount")
    public String toEditAccount(String accountId, HttpSession session){
        Account account = accountService.getAccountByUserId(accountId);
        session.setAttribute("account", account);
        return "account/editMessage";
    }

    @PostMapping("editAccount")
    public String editAccount(String password, String firstname, String lastname, String email, String phone, String address1, String address2, String city, String state, String zip, String country, String languagePreference, String favouriteCategoryId, String listOption, String bannerOption, HttpSession session){
        boolean k = true;

        Account account = (Account)session.getAttribute("account");
        String username = account.getUsername();
        if(!zip.matches("[0-9]+"))
        {
            k=false;
        }
        boolean myList=false;
        if (listOption!=null)
        {
            myList=true;
        }
        boolean myBanner=false;
        if(bannerOption!=null)
        {
            myBanner=true;
        }
        if(k)
        {
            Account newAccount = new Account(username,password,firstname,lastname,email,phone,address1,address2,city,state,zip,country,languagePreference,favouriteCategoryId,myList,myBanner);
            accountService.updateAccountByUserId(newAccount);
        }
        return "redirect:/account/viewAccounts";
    }

    @GetMapping("/resetPassword")
    public String resetPassword(String accountId){
        accountService.resetPasswordByUserId(accountId);
        return "redirect:/account/viewAccounts";
    }

    @GetMapping("/viewAccountLogs")
    public String viewAccountLogs(String accountId, HttpSession session, Model model){
        if(accountId == null) accountId = (String) session.getAttribute("accountId");
        List<Log> addLogList = accountService.getAddLogs(accountId);
        model.addAttribute("addLogList", addLogList);
        List<Log> browseLogList = accountService.getBrowseLogs(accountId);
        model.addAttribute("browseLogList", browseLogList);
        model.addAttribute("accountId", accountId);
        session.setAttribute("accountId", accountId);
        return "account/accountLogs";
    }

    @GetMapping("/deleteBrowseLog")
    public String deleteBrowseLog(String logId){
        accountService.deleteBrowseLogById(logId);
        return "redirect:/account/viewAccountLogs";
    }
    @GetMapping("/deleteAddLog")
    public String deleteAddLog(String logId){
        accountService.deleteAddLogById(logId);
        return "redirect:/account/viewAccountLogs";
    }
}
